# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.utils.encoding import smart_unicode

from async import async_job
from common.channel.db import scan_repeat_no
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# _GATEWAY = 'https://api.jiuritv.com/qralipay/payment?time={}&sign={}'
_GATEWAY = 'https://api.625pay.com/qralipay/payment?time={}&sign={}'
# _QUERY_GATEWAY = 'https://api.jiuritv.com/qralipay/query-order/{}/{}?flash_id={}'
_QUERY_GATEWAY = 'https://api.625pay.com/qralipay/query-order/{}/{}?flash_id={}'

APP_CONF = {
    'KS': {
        'API_KEY': '05d690fe-f336-041a-5918-e63ebc718dba'
    },
    'ZSQP': {
        'API_KEY': '1cdf28ca-4409-db9c-8a1a-984ad55fcead'
    },
    'TTQP': {
        'API_KEY': 'f8c34269-95e5-33c5-c34e-3b1adbe41a07'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, key):
    '''  生成下单签名 '''
    s = '{}{}{}'.format(p_data, int(time.time()), key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    _LOGGER.info(u'ks6pay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, json, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(json.encode('utf8'), params['time'], key)
    m = hashlib.md5()
    m.update(s)
    calculated_sign = m.hexdigest().lower()
    if sign != calculated_sign:
        _LOGGER.info("ks6pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 10000 : 成功
# 10001 : 商户回调队列过长，请商户检查回调
# 10002 : 该用户已被加入姓名黑名单中
# 10003 : 该用户已被加入IP黑名单中
# 10004 : 该用户已被加入设备黑名单中
# 10005 : 该用户已被加入手机号黑名单中
# 10006 : 该用户已被加入支付宝黑名单中
# 10099 : 无法加入请求队列
# 10100 : 商户请求队列过长
# 10101 : 商户请求队列未启动
# 10102 : 商户请求队列未启动
# 10103 : 分配出错
# 10104 : 未找到该商户的可用资源
# 10105 : 请求失败
# 10106 : 验证失败
# 10107 : 创建订单失败
# 20000 : 交易失败
# 30000 : 无效的请求数据
# 30001 : 无效的请求参数
# 30002 : 被禁止的请求
# 40000 : 请求超时
# 40001 : 等待超时
def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/ks6pay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("bill_price", '%.2f' % pay_amount),
        ("extra", 'charge'),
        ("info", {
            "user_id": str(pay.user_id),
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "name": user_info.get('tel') or '',
            "tel": user_info.get('tel') or '',
            "device_type": user_info.get('device_type') or 'android',
            "ali_name": user_info.get('tel') or '',
        })
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _GATEWAY.format(ts, sign)
    _LOGGER.info('ks6pay brefore data: %s', p_data)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('ks6pay rsp data: %s\n%s', gate_url, response.text)
    j = json.loads(response.text)
    url = j['qr_code'].replace('HTTPS://QR.ALIPAY.COM/', 'https://qr.alipay.com/')
    trade_id = j.get('flashid')
    if trade_id is not None:
        order_db.fill_third_id(pay.id, trade_id)
    # if 'https://qr.alipay.com/' in url:
    #     _LOGGER.info('ks6pay_qr_alipay_com')
    #     raise KspayError('ks6pay url qr_alipay_com')
    return {'charge_info': url}


# {
#     "status" : 0
# }
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("ks6pay notify data: %s", data)
    _LOGGER.info("ks6pay notify body: %s", request.body)
    verify_notify_sign(data, smart_unicode(request.body), api_key)
    data = json.loads(smart_unicode(request.body))
    pay_id = data['merchant_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('ks6pay event does not contain pay ID')

    trade_status = int(data['status'])
    trade_no = data.get('flashid')
    total_fee = float(data['payed_money'])

    trade_repeat = data.get('repeat_pay')
    if trade_repeat == 'yes':
        alipay_no = data.get('upstream_order')
        scan_repeat_no('alipay', pay_id, trade_no, alipay_no, total_fee)
        raise Exception('ks6pay trade_repeat : %s' % pay_id)

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    # check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 10000:
        _LOGGER.info('ks6pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    pay_id = pay_order.id
    url = _QUERY_GATEWAY.format(app_id, api_key[-4:], pay_order.third_id.encode('utf8'))
    _LOGGER.info('ks6pay brefore data: %s', url)
    response = requests.get(url)
    _LOGGER.info('ks6pay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['StatusMessage']
        total_fee = float(data['ReceiptPrice']) / 100.0
        trade_no = data['FlashID']
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 1表示用户还没支付,
        # 2表示用户已经支付，
        # 3，表示正在回调商户中，
        # 4，表示订单成功完成，
        # 5，表示创建失败，失败原因见reason，
        # 6，回调过多导致失败，
        # 7，其它错误，错误详细见reason
        if trade_status == u'已完成':
            # check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('ks6pay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
